package com.tang.controller;

import com.tang.common.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @RequestMapping(value = "/loginup")
    @ResponseBody
    public Result login(String username, String password)  {


        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(true);// 默认不记住密码

        //判断是否已经认证
        if(!currentUser.isAuthenticated()) {
            try {
                currentUser.login(token);
                System.out.println("==========登录成功=======");
                return new Result(true, "登录成功");
            } catch (UnknownAccountException e) {
                System.out.println("==========用户名不存在=======");
                return new Result(false, "用户名不存在");
            } catch (DisabledAccountException e) {
                System.out.println("==========您的账户已经被冻结=======");
                return new Result(false, "您的账户已经被冻结");
            } catch (IncorrectCredentialsException e) {
                System.out.println("==========密码错误=======");
                return new Result(false, "密码错误");
            } catch (ExcessiveAttemptsException e) {
                System.out.println("==========您错误的次数太多了吧,封你半小时=======");
                return new Result(false, "您错误的次数太多了吧,封你半小时");
            } catch (RuntimeException e) {
                System.out.println("==========运行异常=======");
                return new Result(false, "运行异常");
            }
        }else{
            return new Result(false,"已经登录");
        }
    }

    @RequestMapping("/logout")
    public String logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
